package com.drinkdelivery.front.service.impl;

import com.drinkdelivery.common.domain.Users;
import com.drinkdelivery.common.exception.CrmebException;
import com.drinkdelivery.common.utils.FrontRedisUtil;
import com.drinkdelivery.common.utils.RequestUtil;
import com.drinkdelivery.front.service.AuthService;
import com.drinkdelivery.front.service.IUsersService;
import com.drinkdelivery.front.service.WxService;
import com.drinkdelivery.common.token.TokenComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 移动端登录服务类
 */
@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private WxService wxService;

    @Autowired
    private IUsersService usersService;

    @Autowired
    private TokenComponent tokenComponent;

    @Autowired
    private FrontRedisUtil frontRedisUtil;


    /**
     * 微信登录小程序授权登录
     */
    @Override
    public Map<String,Object> wechatRoutineLogin(String code) {//todo

        String openId = "testOpenId2";
//        String openId = wxService.getOpenIdFromCode(code);
//        String sessionKey = wxService.getSessionKeyFromCode(code);

        Users user = usersService.findByOpenid(openId);

        if (user == null) {
            user = new Users();
            // 填充用户属性
            user.setUsername("默认名字");
            user.setAvatarUrl("默认头像");
            user.setPhone("13900000000");
            user.setOpenid(openId);

            Integer result = usersService.registerUser(user);
            if (result == null) {
                throw new CrmebException("注册失败，数据库异常");
            }
        }

        // 生成令牌并存储到 Redis
        String token = tokenComponent.createToken(user);
        user.setToken(token);

        Map<String, Object> response = new HashMap<>();
        response.put("statusCode", 200);
        response.put("message", "登录成功");
        response.put("user", user);


        return response;
    }


    /**
     * 用户登出
     *
     * @param request  HTTP请求
     * @return 登出结果
     */
    @Override
    public Map<String, Object> wechatRoutineLogout(HttpServletRequest request) {
        String token = tokenComponent.getToken(request);
        if (token != null && !token.isEmpty()) {
            frontRedisUtil.delete(tokenComponent.getTokenKey(token));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("statusCode", 200);
        result.put("message", "登出成功");

        return result;
    }
}
